package com.koron.order.linepatrol.satellite.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageInfo;
import com.koron.bean.base.Response;
import com.koron.bean.query.PageQuery;
import com.koron.common.core.business.configsettings.utils.ConfigInfoTool;
import com.koron.common.core.config.ThreadLocalContext;
import com.koron.common.core.util.StringUtils;
import com.koron.order.linedefect.base.bean.po.DefectBean;
import com.koron.order.linedefect.base.bean.query.DefectQuery;
import com.koron.order.linedefect.base.service.DefectService;
import com.koron.order.linepatrol.check.bean.po.LinePatrolCheckSatellite;
import com.koron.order.linepatrol.check.bean.query.LinePatrolCheckSatelliteQuery;
import com.koron.order.linepatrol.check.bean.vo.LinePatrolCheckSatelliteVO;
import com.koron.order.linepatrol.check.service.LinePatrolCheckSatelliteService;
import com.koron.order.linepatrol.satellite.bean.dto.LinePatrolSatelliteDTO;
import com.koron.order.linepatrol.satellite.bean.po.LinePatrolSatellite;
import com.koron.order.linepatrol.satellite.bean.query.LinePatrolSatelliteQuery;
import com.koron.order.linepatrol.satellite.mapper.LinePatrolSatelliteMapper;
import com.koron.order.linepatrol.satellite.service.LinePatrolSatelliteService;
import com.koron.order.overhaul.bean.dto.Equipment;
import com.koron.order.risk.base.bean.query.LineRiskQuery;
import com.koron.order.risk.base.bean.vo.LineRiskVO;
import com.koron.order.risk.base.mapper.LineEquipmentMapper;
import com.koron.order.risk.base.service.LineRiskService;
import com.koron.order.risk.feign.LineEquipmentFeign;
import com.koron.order.risk.feign.dto.EquipmentParams;
import org.koron.ebs.mybatis.SessionFactory;
import org.koron.ebs.mybatis.TaskAnnotation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 卫星巡视工单(LinePatrolSatellite)表服务实现类
 *
 * @author jzp
 * @since 2023-02-08 16:47:14
 */
@Service
public class LinePatrolSatelliteServiceImpl implements LinePatrolSatelliteService {


    @Autowired
    private LineEquipmentFeign equipmentFeign;
    @Autowired
  LinePatrolCheckSatelliteService linePatrolCheckSatelliteService;

    @Autowired
    LineRiskService lineRiskService;

    @Autowired
    DefectService defectService;

    public String getCurrDs(){
     return    ThreadLocalContext.get().getCurrDs();
    }
    @Override
    @TaskAnnotation("selectDetailById")
    public LinePatrolSatelliteDTO selectDetailById(SessionFactory factory, String id) {
        LinePatrolSatellite linePatrolSatellite = getById(factory, id);
        LinePatrolSatelliteDTO linePatrolSatelliteDTO = new LinePatrolSatelliteDTO();
        linePatrolSatelliteDTO.setLinePatrolSatellite(linePatrolSatellite);
        if(StringUtils.isNotEmpty(linePatrolSatellite.getCheckId())){
            LinePatrolCheckSatelliteQuery linePatrolCheckSatelliteQuery = new LinePatrolCheckSatelliteQuery();
            linePatrolCheckSatelliteQuery.setId(linePatrolSatellite.getCheckId());
            List<LinePatrolCheckSatellite> list = linePatrolCheckSatelliteService.list(factory, linePatrolCheckSatelliteQuery);
            LinePatrolCheckSatellite checkSatellite = list.stream().findFirst().orElse(new LinePatrolCheckSatellite());
            linePatrolSatelliteDTO.setLinePatrolCheckSatellite(checkSatellite);
        }
        LineRiskQuery lineRiskQuery = new LineRiskQuery();
        lineRiskQuery.setPatrolId(linePatrolSatellite.getId());
        List<LineRiskVO> lineRiskVOS = lineRiskService.list(factory, lineRiskQuery);
        linePatrolSatelliteDTO.setLineRiskOrders(lineRiskVOS);
        DefectQuery defectQuery = new DefectQuery();
        defectQuery.setPatrolId(linePatrolSatellite.getId());
        List<DefectBean> defectBeans = defectService.queryList(factory, defectQuery);
        linePatrolSatelliteDTO.setDefectOrders(defectBeans);
        return linePatrolSatelliteDTO;
    }

    /**
     * 通过ID查询单条数据
     */
    @Override
    @TaskAnnotation("getById")
    public LinePatrolSatellite getById(SessionFactory factory, String id) {
        LinePatrolSatelliteMapper mapper = factory.getMapper(LinePatrolSatelliteMapper.class);
        LinePatrolSatellite linePatrolSatellite = mapper.selectById(id);
        return linePatrolSatellite;
    }

    /**
     * 查询所有数据
     */
    @Override
    @TaskAnnotation("list")
    public List<LinePatrolSatellite> list(SessionFactory factory, LinePatrolSatelliteQuery query) {
        LinePatrolSatelliteMapper mapper = factory.getMapper(LinePatrolSatelliteMapper.class);
        return mapper.selectList(query);
    }

    @Override
    @TaskAnnotation("listByCheckId")
    public List<LinePatrolSatellite> listByCheckId(SessionFactory factory, String checkId) {
        LinePatrolSatelliteQuery linePatrolSatelliteQuery = new LinePatrolSatelliteQuery();
        linePatrolSatelliteQuery.setCheckId(checkId);
        return list(factory, linePatrolSatelliteQuery);
    }

    @Override
    @TaskAnnotation("page")
    public PageInfo<LinePatrolSatellite> page(SessionFactory factory, PageQuery pageQuery, LinePatrolSatelliteQuery query) {
        return LinePatrolSatelliteService.super.page(factory, pageQuery, query);
    }

    /**
     * 新增数据
     */
    @Override
    @TaskAnnotation("save")
    public boolean save(SessionFactory factory, LinePatrolSatellite linePatrolSatellite) {
        if (linePatrolSatellite.getCheckStatus() == null) {
            linePatrolSatellite.setCheckStatus("0");
        }
        LinePatrolSatelliteMapper mapper = factory.getMapper(LinePatrolSatelliteMapper.class);
        return mapper.insertOrUpdate(linePatrolSatellite) > 0;
    }

    @Override
    @TaskAnnotation("saveBatch")
    public boolean saveBatch(SessionFactory factory, List<LinePatrolSatellite> linePatrolSatelliteList) {
        if (CollUtil.isEmpty(linePatrolSatelliteList)) {
            return false;
        }
        LinePatrolSatelliteMapper mapper = factory.getMapper(LinePatrolSatelliteMapper.class);
        return mapper.insertOrUpdateBatch(linePatrolSatelliteList) > 0;
    }

    /**
     * 修改数据
     */
    @Override
    @TaskAnnotation("update")
    public boolean update(SessionFactory factory, LinePatrolSatellite linePatrolSatellite) {
        LinePatrolSatelliteMapper mapper = factory.getMapper(LinePatrolSatelliteMapper.class);
        return mapper.update(linePatrolSatellite) > 0;
    }

    @Override
    public boolean fillCheck(SessionFactory factory, LinePatrolCheckSatelliteVO linePatrolCheckSatelliteVO, List<String> patrolIds) {
        LinePatrolSatelliteMapper mapper = factory.getMapper(LinePatrolSatelliteMapper.class);
        return mapper.fillCheck(linePatrolCheckSatelliteVO, patrolIds) > 0;
    }

    @Override
    public boolean clearCheck(SessionFactory factory, String checkId) {
        LinePatrolSatelliteMapper mapper = factory.getMapper(LinePatrolSatelliteMapper.class);
        return mapper.clearCheck(checkId) > 0;
    }

    /**
     * 通过主键删除数据
     */
    @Override
    @TaskAnnotation("deleteById")
    public boolean deleteById(SessionFactory factory, String id) {
        LinePatrolSatelliteMapper mapper = factory.getMapper(LinePatrolSatelliteMapper.class);
        return mapper.hidden(id) > 0;
    }

    @Override
    @TaskAnnotation("allEquipments")
    public List<Equipment> allEquipments(SessionFactory factory) {
        // 1. 查询根设备
        Map<String, String> config = ConfigInfoTool.getConfigByCode("equipment", "line_root_device");
        String id = config.get("id");
            factory.setDbEnv(getCurrDs());
            LineEquipmentMapper mapper = factory.getMapper(LineEquipmentMapper.class);
            Equipment root = mapper.getById(id);
            List<Equipment> equipmentList = mapper.selectSimpleLineEquipment(root.getLevelPath(), root.getLevel() + 3);
            // 线路设备
            Map<String, Equipment> lineEquipmentMap = new HashMap<>();
            for (Equipment equipment : equipmentList) {
                // 本身equipmentList就是有序的
                // 添加线路设备
                String parentId = equipment.getParentId();
                if (parentId.equals(root.getId())) {
                    if (root.getChildren() == null) {
                        root.setChildren(new ArrayList<>(Collections.singletonList(equipment)));
                    } else {
                        List<Equipment> children = root.getChildren();
                        children.add(equipment);
                    }
                    lineEquipmentMap.put(equipment.getId(), equipment);
                }
                // 添加杆塔
                if (lineEquipmentMap.containsKey(parentId)) {
                    Equipment parent = lineEquipmentMap.get(parentId);
                    if (parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>(Collections.singletonList(equipment)));
                    } else {
                        List<Equipment> children = parent.getChildren();
                        children.add(equipment);
                    }
                }
            }
            List<Equipment> lineEquipments = root.getChildren();
            lineEquipments.forEach(i-> i.getChildren().forEach(j->j.setName(j.getName().replace(j.getParentName(),""))));

            for (Equipment lineEquipment : lineEquipments) {
                List<Equipment> towerEquipments = lineEquipment.getChildren();
                List<String> ids = towerEquipments.stream().map(Equipment::getId).collect(Collectors.toList());

                Response<List<EquipmentParams>> batchBaseParams = equipmentFeign.getBatchBaseParams(ids);
                if (CollUtil.isEmpty(batchBaseParams.getData())) {
                    return lineEquipments;
                }
                List<EquipmentParams> data = batchBaseParams.getData();
                Map<String, EquipmentParams> deptMap = data.stream()
                        .filter(e -> "管理部门".equals(e.getParamName()))
                        .collect(Collectors.toMap(EquipmentParams::getEquipmentId, e -> e, (o1, o2) -> o1));
                for (Equipment equipment : towerEquipments) {
                    EquipmentParams params = deptMap.get(equipment.getId());
                    if(params == null){
                        continue;
                    }
                    equipment.setDeptId(params.getParamResult());
                    equipment.setDeptName(params.getParamValue());
                }


        }
        return lineEquipments;
    }
}
